package com.yang.testservice;

import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Point;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.yang.handle.PhotoHandler;
import com.yang.service.LocalService;

public class MainActivity extends Activity {
	private Intent serviceIntent;
	private LocalService myService = null;
	private Camera mCamera;
	private String str = "Hello";
	private boolean mIsBound = false;

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		System.out.println("MainActivity.onSaveInstanceState()");
		str = "Hello World";
		outState.putString("key", str);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		System.out.println("MainActivity.onSaveInstanceState the key is "
				+ savedInstanceState == null ? "绌�" : savedInstanceState
				.getString("key"));
	}

	@Override
	public Object onRetainNonConfigurationInstance() {
		return str;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mCamera = openFacingBackCamera();
		
		System.out.println("MainActivity.onCreate the key is "
				+ (savedInstanceState == null ? "绌�" : savedInstanceState
						.getString("key")));
		System.out
				.println("MainActivity.onCreate getLastNonConfigurationInstance "
						+ (getLastNonConfigurationInstance() != null ? "绌�"
								: getLastNonConfigurationInstance()));
	}

	private void startMyService() {
		serviceIntent = new Intent(MainActivity.this, LocalService.class);
		startService(serviceIntent);
	}

	public void click(View v) {
		int key = v.getId();
		switch (key) {
		case R.id.button1:
			startMyService();
			doBindService();
			break;
		//case R.id.button3:
		//	break;
		case R.id.button2:
			testcamera();
			break;
		//case R.id.button4:
		//	this.finish();
		//	break;
		default:
			break;
		}

	}

	void doBindService() {
		// Establish a connection with the service. We use an explicit
		// class name because we want a specific service implementation that
		// we know will be running in our own process (and thus won't be
		// supporting component replacement by other applications).
		bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
		mIsBound = true;
	}

	void doUnbindService() {
		if (mIsBound) {
			// Detach our existing connection.
			unbindService(serviceConnection);
			mIsBound = false;
		}
	}
	
	int i = 0;
	void testcamera() {
		if (mCamera != null) {
			SurfaceView dummy = new SurfaceView(getBaseContext());
			try {
				mCamera.setPreviewDisplay(dummy.getHolder());
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		  
	        
		  Parameters parameters = mCamera.getParameters();  
          parameters.setFlashMode(Parameters.FLASH_MODE_ON);//开启  
          parameters.setFocusMode(Parameters.FOCUS_MODE_AUTO);//开启  
          List<Size> SupportedPreviewSizes =
          parameters.getSupportedPreviewSizes();// 获取支持预览照片的尺寸
          int index1 = getPictureSize(SupportedPreviewSizes);
          Size previewSize = SupportedPreviewSizes.get(index1);// 从List取出Size
          parameters.setPreviewSize(previewSize.width, previewSize.height);//设置预览照片的大小
          

          List<Size> supportedPictureSizes =
          parameters.getSupportedPictureSizes();// 获取支持保存图片的尺寸
          int index2 = getPictureSize(supportedPictureSizes);
          Size pictureSize = supportedPictureSizes.get(index2);// 从List取出Size
          parameters.setPictureSize(pictureSize.width, pictureSize.height);
          
            parameters.setJpegQuality(100);
            mCamera.setParameters(parameters);
            mCamera.startPreview();
            
            
            new Thread(new Runnable() {
            	int i = 0;
    			@Override
    			public void run() {
    				//初始化camera并对焦拍照
    		        SystemClock.sleep(500);
    		        for(i = 0; i <10;i++){
    		        mCamera.autoFocus( new Camera.AutoFocusCallback (){    
    	                 public void onAutoFocus(boolean success, Camera camera) { 
    	                	 if(success)//success表示对焦成功
    	                     { 
    	                         Log.i("test", "myAutoFocusCallback: success...");
    	                         mCamera.takePicture(null, null, new PhotoHandler(
    	               					getApplicationContext()));  
    	                         i = 10;
    	                     }
    	                     else
    	                     {
    	                         //未对焦成功
    	                         Log.i("test", "myAutoFocusCallback: 失败了...");
    	                         mCamera.takePicture(null, null, new PhotoHandler(
    	 	               					getApplicationContext()));
    	                         
    	                     }
    	                	 
    	                	  
    	                  }                   
    	             }); 
    		        }
    		        
    		       
    			}
    		}).start();		
		}
	}
	
	private int getPictureSize(List<Size> sizes) {

		// 屏幕的宽度
		Point point = new Point();
        getWindowManager().getDefaultDisplay().getSize(point);
		int screenWidth = point.x;
		int screenHeight = point.y;
		int index = -1;


		for (int i = 0; i < sizes.size(); i++) {
			if (Math.abs(screenWidth - sizes.get(i).width) == 0 && Math.abs(screenHeight - sizes.get(i).height) == 0) {
				index = i;
				break;
			}
		}
		// 当未找到与手机分辨率相等的数值,取列表中间的分辨率
		if (index == -1) {
			index = sizes.size() / 2;
		}


		return index;
	}
		
	private Camera openFacingBackCamera() {
		Camera cam = null;
		Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
		;
		for (int camIdx = 0, cameraCount = Camera.getNumberOfCameras(); camIdx < cameraCount; camIdx++) {
			Camera.getCameraInfo(camIdx, cameraInfo);
			if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
				try {
					
					Parameters parameters = null;  
					cam = Camera.open(camIdx);
					parameters = mCamera.getParameters();  
	                parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);//开启  
	                parameters.setFocusMode(Parameters.FOCUS_MODE_AUTO);
	                List<Size> SupportedPreviewSizes =
	                        parameters.getSupportedPreviewSizes();// 获取支持预览照片的尺寸
	                        int index1 = getPictureSize(SupportedPreviewSizes);
	                        Size previewSize = SupportedPreviewSizes.get(index1);// 从List取出Size
	                        parameters.setPreviewSize(previewSize.width, previewSize.height);//设置预览照片的大小
	                        
	                        List<Size> supportedPictureSizes =
	                        parameters.getSupportedPictureSizes();// 获取支持保存图片的尺寸
	                        int index2 = getPictureSize(supportedPictureSizes);
	                        Size pictureSize = supportedPictureSizes.get(index2);// 从List取出Size
	                        parameters.setPictureSize(pictureSize.width, pictureSize.height);
		            parameters.setJpegQuality(100);
	                //Parameters.ANTIBANDING_AUTO
		            mCamera.setParameters(parameters); 
				} catch (RuntimeException e) {
					e.printStackTrace();
				}
			}
		}

		return cam;

	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		startMyService();
		doBindService();
		if (mCamera != null) {
			mCamera.release();
			mCamera = null;
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		// bindService(serviceIntent, serviceConnection,
		// Context.BIND_AUTO_CREATE);
	}

	ServiceConnection serviceConnection = new ServiceConnection() {

		public void onServiceConnected(ComponentName name, IBinder service) {
			myService = ((LocalService.LocalBinder) service).getService();
		}

		public void onServiceDisconnected(ComponentName name) {
			myService = null;
		}

	};

}
